<template>
  <div class="project-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>Project Management</span>
          <div class="actions">
            <el-input
                v-model="searchQuery"
                placeholder="Search projects..."
                class="search-input"
                clearable
                @input="handleSearch"
            >
              <template #suffix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="openCreateProjectDialog">Create Project</el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTab" class="project-tabs" @tab-click="handleTabClick">
        <el-tab-pane label="All Projects" name="all"></el-tab-pane>
        <el-tab-pane label="Unassigned" name="unassigned"></el-tab-pane>
        <el-tab-pane label="In Progress" name="in_progress"></el-tab-pane>
        <el-tab-pane label="Completed" name="completed"></el-tab-pane>
        <el-tab-pane label="Pending Review" name="pending_review">
          <template #label>
            <span>Pending Review</span>
            <el-badge v-if="pendingReviewCount > 0" :value="pendingReviewCount" class="review-badge" />
          </template>
        </el-tab-pane>
      </el-tabs>

      <el-table
          :data="paginatedProjects"
          border
          style="width: 100%"
          v-loading="loading"
          max-height="800px"
          :key="tableKey"
      >
        <el-table-column prop="title" label="Project Title" min-width="150" />
        <el-table-column prop="category" label="Category" width="120" />
        <el-table-column prop="assigneeName" label="Assigned Student" width="120">
          <template #default="scope">
            <span v-if="scope.row.assigneeName">{{ scope.row.assigneeName }}</span>
            <el-tag v-else type="info">Unassigned</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="Status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="Start Time" width="160" />
        <el-table-column prop="endTime" label="End Time" width="160" />
        <el-table-column label="Actions" width="280" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewProjectDetails(scope.row)">
              <el-icon><View /></el-icon>Details
            </el-button>
            <el-button
                v-if="scope.row.status !== 'Pending Review' && scope.row.status !== 'Review Rejected'"
                type="success"
                size="small"
                @click="openAssignDialog(scope.row)"
                :disabled="!!scope.row.assigneeId"
            >
              <el-icon><CirclePlus /></el-icon>Assign
            </el-button>
            <el-button
                v-if="scope.row.status === 'Pending Review'"
                type="success"
                size="small"
                @click="openReviewDialog(scope.row)"
            >
              <el-icon><Check /></el-icon>Review
            </el-button>
            <el-button 
                type="warning" 
                size="small" 
                @click="editProject(scope.row)"
                :disabled="hasEvaluation(scope.row) || scope.row.status === 'Review Rejected'"
                :title="hasEvaluation(scope.row) ? 'Cannot edit evaluated project' : scope.row.status === 'Review Rejected' ? 'Cannot edit project in Review Rejected status' : 'Edit project'"
            >
              <el-icon><Edit /></el-icon>Edit
            </el-button>
            <el-button 
                type="danger" 
                size="small" 
                @click="confirmDeleteProject(scope.row)"
                :disabled="!canDeleteProject(scope.row)"
                :title="getDeleteButtonTitle(scope.row)"
            >
              <el-icon><Delete /></el-icon>Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalProjects"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Project Details Dialog -->
    <el-dialog
        v-model="detailsDialogVisible"
        title="Project Details"
        width="60%"
        destroy-on-close
        @closed="handleProjectDialogClosed"
    >
      <el-descriptions
          v-if="currentProject"
          :column="2"
          border
      >
        <el-descriptions-item label="Project Title">{{ currentProject.title }}</el-descriptions-item>
        <el-descriptions-item label="Project Status">
          <el-tag :type="getStatusType(currentProject.status)">
            {{ currentProject.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Project Category">{{ currentProject.category || 'Uncategorized' }}</el-descriptions-item>
        <el-descriptions-item label="Assigned Student">
          <span v-if="currentProject.assigneeName">{{ currentProject.assigneeName }}</span>
          <el-tag v-else type="info">Unassigned</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Start Time">{{ currentProject.startTime || 'Not Set' }}</el-descriptions-item>
        <el-descriptions-item label="End Time">{{ currentProject.endTime || 'Not Set' }}</el-descriptions-item>
        <el-descriptions-item label="Create Time">{{ currentProject.createTime }}</el-descriptions-item>
        <el-descriptions-item label="Update Time">{{ currentProject.updateTime }}</el-descriptions-item>
        <el-descriptions-item label="Project Description" :span="2">
          <div class="project-description">{{ currentProject.description || 'No Description' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="Project Requirements" :span="2">
          <div class="project-requirements">{{ currentProject.requirements || 'No Requirements' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="Related Resources" :span="2">
          <div class="project-resources">{{ currentProject.resources || 'No Resources' }}</div>
        </el-descriptions-item>
      </el-descriptions>

      <!-- Project Evaluation Section -->
      <div v-if="currentProject && (currentProject.status === 'Completed' || currentProject.status === 'Waiting for Review')" class="project-evaluation-section">
        <div class="section-header">
          <h3>Project Evaluation</h3>
        </div>
        <div v-loading="evaluationLoading">
          <el-form v-if="!currentEvaluation" :model="evaluationForm" label-width="80px">
            <el-form-item label="Score">
              <el-input-number
                  v-model="evaluationForm.score"
                  :min="0"
                  :max="100"
                  :step="1"
                  controls-position="right"
              />
              <span style="margin-left: 10px;">points</span>
            </el-form-item>
            <el-form-item label="Comment">
              <el-input
                  v-model="evaluationForm.comment"
                  type="textarea"
                  :rows="3"
                  placeholder="Enter your evaluation of the student's completion"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitEvaluation">Submit Evaluation</el-button>
            </el-form-item>
          </el-form>

          <el-descriptions v-else border :column="1" class="evaluation-details">
            <el-descriptions-item label="Score">
              {{ currentEvaluation.score }} points
            </el-descriptions-item>
            <el-descriptions-item label="Comment">
              {{ currentEvaluation.comment || 'No comment' }}
            </el-descriptions-item>
            <el-descriptions-item label="Evaluation Time">
              {{ currentEvaluation.evaluationTime }}
            </el-descriptions-item>
            <el-descriptions-item>
              <el-button type="warning" @click="editEvaluation">Edit Evaluation</el-button>
              <el-button type="danger" @click="deleteEvaluation">Delete Evaluation</el-button>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <div class="task-section" v-if="currentProject && currentProject.id">
        <div class="task-header">
          <h3>Associated Task List</h3>
          <div class="button-group" v-if="!hasEvaluation(currentProject) && currentProject.status !== 'Review Rejected' && currentProject.status !== 'Waiting for Review'">
            <el-button type="primary" size="small" @click="openAddTaskDialog">
              <el-icon><Plus /></el-icon>Add Task
            </el-button>
          </div>
        </div>

        <el-table
            :data="projectTasks"
            border
            style="width: 100%"
            v-loading="tasksLoading"
        >
          <el-table-column prop="title" label="Task Title" min-width="120" />
          <el-table-column prop="priority" label="Priority" width="80">
            <template #default="scope">
              <el-tag :type="getTaskPriorityType(scope.row.priority)">
                {{ scope.row.priority || 'Medium' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="assigneeName" label="Assigned Student" width="120">
            <template #default="scope">
              <span v-if="scope.row.assigneeName">{{ scope.row.assigneeName }}</span>
              <el-tag v-else type="info">Unassigned</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="completed" label="File Submission" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.completed || scope.row.reviewNeeded ? 'success' : 'info'">
                {{ scope.row.completed || scope.row.reviewNeeded ? 'Submitted' : 'Not Submitted' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="Start Time" width="150">
            <template #default="scope">
              <span>{{ scope.row.startTime || 'Not Set' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="End Time" width="150">
            <template #default="scope">
              <span>{{ scope.row.endTime || 'Not Set' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="Actions" width="200" fixed="right">
            <template #default="scope">
              <el-button 
                  type="primary" 
                  size="small" 
                  @click="viewTaskSubmissions(scope.row)"
                  title="View task files"
              >
                <el-icon><Document /></el-icon>Files
              </el-button>
              <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDeleteTask(scope.row)"
                  :disabled="!canDeleteProject(currentProject)"
                  :title="!canDeleteProject(currentProject) ? 'Cannot delete task in this project' : 'Delete task'"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="empty-task" v-if="projectTasks.length === 0 && !tasksLoading">
          <el-empty description="No associated tasks" />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">Close</el-button>
          <el-button 
            v-if="currentProject && canDeleteProject(currentProject)"
            type="danger" 
            @click="confirmDeleteProject(currentProject)"
          >
            <el-icon><Delete /></el-icon>Delete Project
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Create/Edit Project Dialog -->
    <el-dialog
        v-model="projectFormDialogVisible"
        :title="isEditing ? 'Edit Project' : 'Create Project'"
        width="60%"
        destroy-on-close
    >
      <el-form
          ref="projectFormRef"
          :model="projectForm"
          :rules="projectRules"
          label-width="100px"
      >
        <el-form-item label="Project Title" prop="title">
          <el-input v-model="projectForm.title" placeholder="Enter project title" />
        </el-form-item>
        <el-form-item label="Project Category" prop="category">
          <el-input v-model="projectForm.category" placeholder="Enter project category" />
        </el-form-item>
        <el-form-item label="Project Description" prop="description">
          <el-input
              v-model="projectForm.description"
              placeholder="Enter project description"
              type="textarea"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="Project Requirements" prop="requirements">
          <el-input
              v-model="projectForm.requirements"
              placeholder="Enter project requirements"
              type="textarea"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="Related Resources" prop="resources">
          <el-input
              v-model="projectForm.resources"
              placeholder="Enter related resources"
              type="textarea"
              :rows="3"
          />
        </el-form-item>
        <el-form-item label="Time Range" prop="timeRange">
          <div style="display: flex; gap: 10px; align-items: center;">
            <el-date-picker
                v-model="startTime"
                type="datetime"
                placeholder="Start Time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 0, 1, 9, 0, 0)"
                style="width: 100%;"
                :disabled-date="disablePastDates"
                @change="validateTimeRange"
            />
            <span>to</span>
            <el-date-picker
                v-model="endTime"
                type="datetime"
                placeholder="End Time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 0, 1, 18, 0, 0)"
                style="width: 100%;"
                :disabled-date="disableBeforeStartDate"
            />
          </div>
        </el-form-item>
      </el-form>

      <!-- Add Task Area when Creating Project -->
      <div class="task-create-section">
        <div class="section-header">
          <h3>Project Tasks</h3>
          <div class="button-group">
            <el-button 
              type="primary" 
              size="small" 
              @click="openNewTaskDialog"
              :disabled="isEditing && (projectForm.status === 'Review Rejected' || projectForm.status === 'Waiting for Review')"
              :title="isEditing && projectForm.status === 'Review Rejected' ? 'Cannot add tasks to Review Rejected project' : isEditing && projectForm.status === 'Waiting for Review' ? 'Cannot add tasks to project Waiting for Review' : 'Add new task'"
            >
              <el-icon><Plus /></el-icon>Add Task
            </el-button>
          </div>
        </div>

        <el-table
            :data="newProjectTasks"
            border
            style="width: 100%; margin-top: 15px;"
        >
          <el-table-column prop="title" label="Task Title" min-width="120" />
          <el-table-column prop="priority" label="Priority" width="80">
            <template #default="scope">
              <el-tag :type="getTaskPriorityType(scope.row.priority)">
                {{ scope.row.priority || 'Medium' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="Start Time" width="150">
            <template #default="scope">
              <span>{{ scope.row.startTime || 'Not Set' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="End Time" width="150">
            <template #default="scope">
              <span>{{ scope.row.endTime || 'Not Set' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="Actions" width="200">
            <template #default="scope">
              <el-button 
                type="warning" 
                size="small" 
                @click="editNewTask(scope.$index)"
                :disabled="isEditing && (projectForm.status === 'Review Rejected' || projectForm.status === 'Waiting for Review')"
                :title="isEditing && projectForm.status === 'Review Rejected' ? 'Cannot edit tasks in Review Rejected project' : isEditing && projectForm.status === 'Waiting for Review' ? 'Cannot edit tasks in project Waiting for Review' : 'Edit task'"
              >
                <el-icon><Edit /></el-icon>Edit
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="removeNewTask(scope.$index)"
                :disabled="isEditing && (projectForm.status === 'Review Rejected' || projectForm.status === 'Waiting for Review')"
                :title="isEditing && projectForm.status === 'Review Rejected' ? 'Cannot delete tasks in Review Rejected project' : isEditing && projectForm.status === 'Waiting for Review' ? 'Cannot delete tasks in project Waiting for Review' : 'Delete task'"
              >
                <el-icon><Delete /></el-icon>Delete
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div v-if="newProjectTasks.length === 0" class="empty-tasks-tip">
          <el-empty description='No tasks yet, click "Add Task" to create' />
        </div>
      </div>

      <!-- Add task loading tips when editing project -->
      <div v-if="isEditing" class="task-loading-tip">
        <el-alert
            title="Associated tasks automatically loaded"
            type="info"
            :closable="false"
            show-icon
        >
          <template #default>
            <p>Here you can manage the tasks of the project, including adding new tasks or editing existing ones.</p>
            <p>All changes will be saved after clicking OK.</p>
            <p v-if="projectForm.assigneeId" class="auto-assign-tip">
              <strong>Note:</strong> This project has been assigned to a student, new tasks will be automatically assigned to that student.
            </p>
          </template>
        </el-alert>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="projectFormDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="submitProjectForm">OK</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Assign Project to Student Dialog -->
    <el-dialog
        v-model="assignDialogVisible"
        title="Assign Project to Student"
        width="40%"
        destroy-on-close
    >
      <div v-loading="studentsLoading">
        <el-alert
            v-if="students.length === 0 && !studentsLoading"
            title="No assignable students"
            type="warning"
            :closable="false"
            show-icon
        />
        <div v-if="students.length === 0 && !studentsLoading" style="text-align: center; margin-top: 10px;">
          <el-button type="primary" size="small" @click="fetchStudents">
            <el-icon><Refresh /></el-icon>Refresh Student List
          </el-button>
        </div>
        <el-form v-else label-width="80px">
          <el-form-item label="Select Student">
            <div style="display: flex; gap: 10px;">
              <el-select
                  v-model="selectedStudentId"
                  placeholder="Select a student"
                  style="width: 100%"
                  filterable
              >
                <el-option
                    v-for="student in students"
                    :key="student.id"
                    :label="student.name ? `${student.name}${student.studentId ? ` (${student.studentId})` : ''}` : student.username"
                    :value="student.id"
                />
              </el-select>
              <el-button type="primary" @click="fetchStudents" :loading="studentsLoading">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleAssignProject" :disabled="!selectedStudentId">OK</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Add Task Dialog -->
    <el-dialog
        v-model="taskFormVisible"
        title="Add Task"
        width="50%"
        destroy-on-close
    >
      <el-form
          ref="taskFormRef"
          :model="taskForm"
          label-width="100px"
      >
        <el-form-item label="Task Title" prop="title" required>
          <el-input v-model="taskForm.title" placeholder="Enter task title" />
        </el-form-item>
        <el-form-item label="Task Description" prop="description">
          <el-input
              v-model="taskForm.description"
              placeholder="Enter task description"
              type="textarea"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="Priority" prop="priority">
          <el-select v-model="taskForm.priority" placeholder="Select priority">
            <el-option label="High" value="High" />
            <el-option label="Medium" value="Medium" />
            <el-option label="Low" value="Low" />
          </el-select>
        </el-form-item>
        <!-- 添加时间选择组件 -->
        <el-form-item label="Time Range" prop="timeRange">
          <div style="display: flex; gap: 10px; align-items: center;">
            <el-date-picker
                v-model="taskForm.startTime"
                type="datetime"
                placeholder="Start Time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 0, 1, 9, 0, 0)"
                style="width: 100%;"
                :disabled-date="disablePastDates"
                @change="validateTimeRange"
            />
            <span>to</span>
            <el-date-picker
                v-model="taskForm.endTime"
                type="datetime"
                placeholder="End Time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 0, 1, 18, 0, 0)"
                style="width: 100%;"
                :disabled-date="disableBeforeStartDate"
                @change="validateTimeRange"
            />
          </div>
        </el-form-item>
        <!-- 移除状态选择框，自动设置为Not Started -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="taskFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="submitTaskForm">OK</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Add Task Dialog when Creating Project -->
    <el-dialog
        v-model="newTaskFormVisible"
        :title="editingTaskIndex >= 0 ? 'Edit Task' : 'Add Task'"
        width="50%"
        destroy-on-close
    >
      <el-form
          ref="newTaskFormRef"
          :model="newTaskForm"
          label-width="100px"
      >
        <el-form-item label="Task Title" prop="title" required>
          <el-input v-model="newTaskForm.title" placeholder="Enter task title" />
        </el-form-item>
        <el-form-item label="Task Description" prop="description">
          <el-input
              v-model="newTaskForm.description"
              placeholder="Enter task description"
              type="textarea"
              :rows="4"
          />
        </el-form-item>
        <el-form-item label="Priority" prop="priority">
          <el-select v-model="newTaskForm.priority" placeholder="Select priority">
            <el-option label="High" value="High" />
            <el-option label="Medium" value="Medium" />
            <el-option label="Low" value="Low" />
          </el-select>
        </el-form-item>
        <!-- 移除状态选择，让任务状态自动更新而不是手动设置 -->
        <el-form-item label="Time Range" prop="timeRange">
          <div style="display: flex; gap: 10px; align-items: center;">
            <el-date-picker
                v-model="newTaskForm.startTime"
                type="datetime"
                placeholder="Start Time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 0, 1, 9, 0, 0)"
                style="width: 100%;"
                :disabled-date="disablePastDates"
                @change="validateTaskTimeRange"
            />
            <span>to</span>
            <el-date-picker
                v-model="newTaskForm.endTime"
                type="datetime"
                placeholder="End Time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :default-time="new Date(2000, 0, 1, 18, 0, 0)"
                style="width: 100%;"
                :disabled-date="disableBeforeTaskStartDate"
                @change="validateTaskTimeRange"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="newTaskFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="addNewTask">OK</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Batch Select Tasks Dialog -->
    <el-dialog
        v-model="batchSelectTasksVisible"
        title="Batch Select Tasks"
        width="70%"
        destroy-on-close
    >
      <div v-loading="availableTasksLoading">
        <el-input
            v-model="taskSearchQuery"
            placeholder="Search tasks..."
            prefix-icon="el-icon-search"
            clearable
            style="margin-bottom: 15px;"
        />

        <el-table
            :data="filteredAvailableTasks"
            border
            style="width: 100%"
            @selection-change="handleTaskSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="title" label="Task Title" min-width="120" />
          <el-table-column prop="priority" label="Priority" width="80">
            <template #default="scope">
              <el-tag :type="getTaskPriorityType(scope.row.priority)">
                {{ scope.row.priority || 'Medium' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="Description" min-width="200" show-overflow-tooltip />
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchSelectTasksVisible = false">Cancel</el-button>
          <el-button type="primary" @click="addSelectedTasks">OK</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Add Task Submission Records Dialog -->
    <el-dialog
        v-model="submissionsDialogVisible"
        title="Task Submission Records"
        width="70%"
        destroy-on-close
        @closed="handleSubmissionsDialogClosed"
    >
      <div v-if="currentSubmissionTask" class="task-info">
        <h3>Task Information</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="Task Title">{{ currentSubmissionTask.title }}</el-descriptions-item>
          <el-descriptions-item label="Task Progress">
            <el-tag :type="getTaskStatusType(currentSubmissionTask.status)">
              {{ currentSubmissionTask.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Assigned Student">
            <span v-if="currentSubmissionTask.assigneeName">{{ currentSubmissionTask.assigneeName }}</span>
            <el-tag v-else type="info">Unassigned</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Start Time">{{ currentSubmissionTask.startTime || 'Not Set' }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div v-if="submissions.length > 0" class="submission-list">
        <h3>Submission Records ({{submissions.length}})</h3>
        <el-table :data="submissions" border style="width: 100%">
          <el-table-column prop="originalFilename" label="File Name" min-width="200" />
          <el-table-column prop="fileSize" label="Size" width="120">
            <template #default="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="fileType" label="Type" width="120" />
          <el-table-column prop="submitterName" label="Submitter" width="120" />
          <el-table-column prop="submissionTime" label="Submission Time" width="160" />
          <el-table-column label="Actions" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="downloadSubmission(scope.row)">
                Download
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else class="no-submissions">
        <el-empty description="No submission records" />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="submissionsDialogVisible = false">Close</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Review Project Application Dialog -->
    <el-dialog
        v-model="reviewDialogVisible"
        title="Review Project Application"
        width="50%"
        destroy-on-close
    >
      <div v-if="projectToReview" class="review-content">
        <el-descriptions
            title="Project Application Information"
            :column="1"
            border
        >
          <el-descriptions-item label="Project Title">{{ projectToReview.title }}</el-descriptions-item>
          <el-descriptions-item label="Applicant Student">{{ projectToReview.assigneeName }}</el-descriptions-item>
          <el-descriptions-item label="Project Category">{{ projectToReview.category || 'Uncategorized' }}</el-descriptions-item>
          <el-descriptions-item label="Application Time">{{ projectToReview.createTime }}</el-descriptions-item>
          <el-descriptions-item label="Project Description">
            <div class="project-description">{{ projectToReview.description || 'No Description' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="Project Requirements">
            <div class="project-requirements">{{ projectToReview.requirements || 'No Requirements' }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">Cancel</el-button>
          <el-button type="danger" @click="rejectProjectApplication" :loading="reviewing">Reject Application</el-button>
          <el-button type="success" @click="approveProjectApplication" :loading="reviewing">Approve Application</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { useUserStore } from '../../stores/user';
import {
  Search,
  View,
  Edit,
  CirclePlus,
  Plus,
  Refresh,
  Document,
  Check,
  Delete
} from '@element-plus/icons-vue';
import {
  getSupervisorProjects,
  getSupervisorProjectsByStatus,
  createProject,
  updateProject,
  deleteProject,
  getProjectDetail,
  assignProjectToStudent,
  getPendingReviewProjects,
  reviewProjectApplication,
  getProjectEvaluation,
  evaluateProject,
  deleteProjectEvaluation,
  updateProjectStatus,
  type Project,
  type ProjectEvaluation
} from '../../api/project';
import { 
  getProjectTasks, 
  createTask, 
  deleteTask as deleteTaskApi,
  updateTask,
  getAvailableTasks,
  assignTaskToStudent,
  type Task,
  getTaskSubmissions,
  type TaskSubmission,
  updateTaskStatus as updateTaskStatusApi
} from '../../api/task';
import { getStudents } from '../../api/student';
import type { FormInstance, FormRules } from 'element-plus';
import type { StudentDTO } from '../../api/student';
import { useRoute } from 'vue-router';

const userStore = useUserStore();
const route = useRoute();

// State variables
const loading = ref<boolean>(false);
const searchQuery = ref<string>('');
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const totalProjects = ref<number>(0);
const projects = ref<Project[]>([]);
const activeTab = ref<string>('all');
const detailsDialogVisible = ref<boolean>(false);
const projectFormDialogVisible = ref<boolean>(false);
const isEditing = ref<boolean>(false);
const currentProject = ref<Project | null>(null);
const projectForm = ref<Partial<Project>>({});
const startTime = ref<string | null>(null);
const endTime = ref<string | null>(null);
const assignDialogVisible = ref<boolean>(false);
const selectedStudentId = ref<number | null>(null);
const students = ref<StudentDTO[]>([]);
const projectToAssign = ref<Project | null>(null);
const projectFormRef = ref<FormInstance>();
const studentsLoading = ref(false);
const pendingReviewCount = ref<number>(0);

// Review related variables
const reviewDialogVisible = ref<boolean>(false);
const projectToReview = ref<Project | null>(null);
const reviewing = ref<boolean>(false);

// Task related variables
const projectTasks = ref<Task[]>([]);
const tasksLoading = ref<boolean>(false);
const tasksLoadError = ref<string | null>(null);
const taskFormVisible = ref<boolean>(false);
const taskForm = ref({
  title: '',
  description: '',
  priority: 'Medium',
  status: 'Not Started',
  supervisorId: userStore.user.id,
  projectId: null as number | null,
  assigneeId: null,
  completed: false
});
const taskFormRef = ref<FormInstance>();

// Task variables when creating project
const newProjectTasks = ref<any[]>([]);
const newTaskFormVisible = ref<boolean>(false);
const newTaskForm = ref({
  title: '',
  description: '',
  priority: 'Medium',
  status: 'Not Started',
  startTime: null as string | null,
  endTime: null as string | null
});
const editingTaskIndex = ref<number>(-1);
const newTaskFormRef = ref<FormInstance>();

// Form validation rules
const projectRules = ref<FormRules>({
  title: [
    { required: true, message: 'Please enter project title', trigger: 'blur' },
    { min: 2, max: 100, message: 'Length should be 2 to 100 characters', trigger: 'blur' }
  ]
  // 移除状态验证规则
});

// Batch select tasks dialog
const batchSelectTasksVisible = ref<boolean>(false);
const availableTasksLoading = ref<boolean>(false);
const taskSearchQuery = ref<string>('');
const availableTasks = ref<Task[]>([]);
const selectedTasks = ref<Task[]>([]);

// Task submission records related
const submissionsDialogVisible = ref<boolean>(false);
const submissions = ref<TaskSubmission[]>([]);
const currentSubmissionTask = ref<Task | null>(null);

// Evaluation related variables
const evaluationLoading = ref(false);
const currentEvaluation = ref<ProjectEvaluation | null>(null);
const evaluationForm = ref({
  score: 80,
  comment: ''
});

// Add a reactive reference for table key
const tableKey = ref(0);

// Compute filtered available tasks
const filteredAvailableTasks = computed(() => {
  if (!taskSearchQuery.value) return availableTasks.value;
  
  const query = taskSearchQuery.value.toLowerCase();
  return availableTasks.value.filter(task => 
    task.title?.toLowerCase().includes(query) || 
    task.description?.toLowerCase().includes(query)
  );
});

// Initialize data
onMounted(() => {
  fetchProjects();
  fetchStudents();
  checkPendingReviews();
  
  const projectId = route.query.projectId;
  if (projectId) {
    console.log(`URL contains projectId parameter: ${projectId}, loading project details...`);
    loadProjectById(Number(projectId));
  }
});

const loadProjectById = async (projectId: number) => {
  try {
    loading.value = true;
    const project = await getProjectDetail(projectId);
    if (project) {
      viewProjectDetails(project);
    } else {
      ElMessage.warning('Project not found');
    }
  } catch (error) {
    console.error('Failed to load project details:', error);
    ElMessage.error('Failed to load project details, please try again later');
  } finally {
    loading.value = false;
  }
};

// Fetch project data
const fetchProjects = async () => {
  loading.value = true;
  try {
    let data;
    if (activeTab.value === 'all') {
      data = await getSupervisorProjects(userStore.user.id);
    } else if (activeTab.value === 'pending_review') {
      data = await getPendingReviewProjects(userStore.user.id);
      pendingReviewCount.value = data?.length || 0;
    } else if (activeTab.value === 'unassigned') {
      // For unassigned, we need to fetch all projects and filter them
      const allProjects = await getSupervisorProjects(userStore.user.id);
      data = allProjects.filter(project => !project.assigneeId);
    } else if (activeTab.value === 'in_progress') {
      // For in_progress tab, use "In Progress" status (with space)
      data = await getSupervisorProjectsByStatus(userStore.user.id, 'In Progress');
    } else if (activeTab.value === 'completed') {
      // For completed tab, use "Completed" status
      data = await getSupervisorProjectsByStatus(userStore.user.id, 'Completed');
    } else {
      // For other tabs, capitalize the first letter of the status
      const status = activeTab.value.charAt(0).toUpperCase() + activeTab.value.slice(1);
      data = await getSupervisorProjectsByStatus(userStore.user.id, status);
    }
    
    // Calculate completion percentage for each project
    for (const project of data || []) {
      project.completionPercentage = calculateProjectCompletionPercentage(project);
    }
    
    // 检查已完成项目的评价状态
    if (data && data.length > 0) {
      // 首先创建一个包含所有已完成项目的数组
      const completedProjects = data.filter(project => 
        project.status === 'Completed' || project.status === 'Waiting for Review'
      );
      
      // 对每个已完成项目检查评价状态
      if (completedProjects.length > 0) {
        console.log(`检查 ${completedProjects.length} 个已完成项目的评价状态`);
        
        for (const project of completedProjects) {
          try {
            // 尝试获取项目评价，设置评价状态标记
            const evaluation = await getProjectEvaluation(project.id);
            if (evaluation && evaluation.id) {
              console.log(`项目 ${project.id} 有评价`, evaluation);
              project.hasEvaluation = true;
            } else {
              project.hasEvaluation = false;
            }
          } catch (error) {
            // 如果获取评价失败（如404），表示项目没有评价
            project.hasEvaluation = false;
            console.log(`项目 ${project.id} 没有评价`);
          }
        }
      }
    }
    
    // 修改排序逻辑：未完成的项目排在前面，已完成的项目排在后面
    const sortedData = [...(data || [])].sort((a, b) => {
      // 定义状态优先级：未分配 -> 进行中 -> 待检查 -> 已完成
      const getStatusPriority = (project) => {
        if (!project.status) return 0;
        
        // 未分配状态（没有学生被分配到该项目）
        if (!project.assigneeId) return 0;
        
        // 进行中状态
        if (project.status === 'In Progress') return 1;
        
        // 待检查状态
        if (project.status === 'Pending Review' || project.status === 'Waiting for Review') return 2;
        
        // 已完成状态
        if (project.status === 'Completed') return 3;
        
        return 0; // 其他状态默认为最高优先级
      };
      
      const priorityA = getStatusPriority(a);
      const priorityB = getStatusPriority(b);
      
      // 按状态优先级排序
      if (priorityA !== priorityB) {
        return priorityA - priorityB;
      }
      
      // 相同状态下按完成度百分比降序排序
      return b.completionPercentage - a.completionPercentage;
    });
    
    projects.value = sortedData;
    // totalProjects will be set by paginatedProjects computed property
    if (sortedData.length > 0) {
      ElMessage.success('Successfully retrieved project data');
    } else {
      ElMessage.info(`No ${activeTab.value.replace('_', ' ')} projects found`);
    }
  } catch (error) {
    console.error('Failed to get project data:', error);
    ElMessage.error('Failed to get project data, please try again later');
  } finally {
    loading.value = false;
  }
};

// Calculate project completion percentage based on task completion
const calculateProjectCompletionPercentage = (project) => {
  // If the project status is 'Completed', it's 100% complete
  if (project.status === 'Completed') {
    return 100;
  }
  
  // If the project is 'Not Started', it's 0% complete
  if (project.status === 'Not Started') {
    return 0;
  }
  
  // For 'In Progress' projects, calculate based on task completion
  if (project.completedTaskCount !== undefined && project.totalTaskCount !== undefined) {
    return project.totalTaskCount > 0 
      ? (project.completedTaskCount / project.totalTaskCount) * 100 
      : 0;
  }
  
  // Default percentages for different statuses if task counts aren't available
  switch (project.status) {
    case 'In Progress': return 50;
    case 'Waiting for Review': return 90;
    case 'Pending Review': return 80;
    case 'Completed': return 100;
    default: return 25;
  }
};

// Filter projects based on search
const filteredProjects = computed(() => {
  if (!searchQuery.value) return projects.value;
  
  const query = searchQuery.value.toLowerCase();
  return projects.value.filter(project => 
    project.title?.toLowerCase().includes(query) || 
    project.description?.toLowerCase().includes(query) || 
    project.category?.toLowerCase().includes(query) ||
    (project.assigneeName && project.assigneeName.toLowerCase().includes(query))
  );
});

// Apply pagination to filtered projects
const paginatedProjects = computed(() => {
  // Update totalProjects value to match filtered projects count
  totalProjects.value = filteredProjects.value.length;
  
  // Calculate start and end indices for the current page
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = Math.min(startIndex + pageSize.value, filteredProjects.value.length);
  
  console.log(`Pagination: page ${currentPage.value}, size ${pageSize.value}, showing ${startIndex + 1}-${endIndex} of ${totalProjects.value}`);
  
  // Return the sliced array for the current page
  return filteredProjects.value.slice(startIndex, endIndex);
});

// Handler functions - these will be implemented later
const handleSearch = () => {
  currentPage.value = 1;
};

// Update the handleSizeChange function to increment the key
const handleSizeChange = (newSize: number) => {
  console.log('Page size changed from', pageSize.value, 'to', newSize);
  pageSize.value = newSize;
  currentPage.value = 1; // Reset to first page when changing page size
  
  // Force reactivity update by making a shallow copy of the filtered projects
  const temp = [...filteredProjects.value];
  filteredProjects.value = temp;
  
  // Force table re-render
  tableKey.value += 1;
  
  console.log('Updated pageSize:', pageSize.value);
  console.log('Updated currentPage:', currentPage.value);
  console.log('Total projects:', totalProjects.value);
  console.log('Displayed projects count:', paginatedProjects.value.length);
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
};

const handleTabClick = () => {
  currentPage.value = 1;
  fetchProjects();
};

const openCreateProjectDialog = () => {
  isEditing.value = false;
  projectForm.value = {
    title: '',
    description: '',
    category: '',
    requirements: '',
    resources: '',
    status: 'Not Started', // 确保设置为Not Started
    supervisorId: userStore.user.id
  };
  startTime.value = null;
  endTime.value = null;
  // Clear task list
  newProjectTasks.value = [];
  projectFormDialogVisible.value = true;
};

const viewProjectDetails = async (project: Project) => {
  try {
    loading.value = true;
    // 清空任务数据，确保每次查看详情都会重新加载
    projectTasks.value = [];
    tasksLoadError.value = null;
    currentEvaluation.value = null;
    
    currentProject.value = await getProjectDetail(project.id);
    detailsDialogVisible.value = true;
    
    // Load project-related tasks
    fetchProjectTasks(project.id);
    
    // Load project evaluation (if project status is completed)
    if (currentProject.value.status === 'Completed') {
      loadProjectEvaluation(project.id);
    }
  } catch (error) {
    console.error('Failed to get project details:', error);
    ElMessage.error('Failed to get project details');
  } finally {
    loading.value = false;
  }
};

// Get project-related task list
const fetchProjectTasks = async (projectId: number) => {
  tasksLoading.value = true;
  tasksLoadError.value = null; // 重置错误状态
  
  try {
    console.log('Fetching tasks for project ID:', projectId);
    const tasks = await getProjectTasks(projectId);
    
    if (tasks && tasks.length > 0) {
      console.log(`Successfully retrieved ${tasks.length} tasks for project ${projectId}`);
      
      // 按照结束时间排序任务
      tasks.sort((a, b) => {
        // 首先按照结束时间排序
        if (a.endTime && b.endTime) {
          const dateA = new Date(a.endTime);
          const dateB = new Date(b.endTime);
          return dateB.getTime() - dateA.getTime(); 
        } else if (a.endTime) {
          return -1;
        } else if (b.endTime) {
          return 1;
        } else {

          const dateA = a.createTime ? new Date(a.createTime) : new Date(0);
          const dateB = b.createTime ? new Date(b.createTime) : new Date(0);
          return dateB.getTime() - dateA.getTime();
        }
      });
      
      // 检查并自动更新过期任务的状态
      tasks.forEach(task => {
        if (task.endTime && task.status !== 'Completed') {
          const endDate = new Date(task.endTime);
          const now = new Date();
          if (endDate < now) {
            updateTaskStatus(task.id, 'Completed');
            task.status = 'Completed';
          }
        }
      });
    } else {
      console.log(`No tasks found for project ${projectId}`);
    }
    
    projectTasks.value = tasks || [];
  } catch (error: any) {
    console.error('Failed to get project-related tasks:', error);
    // 记录错误信息
    tasksLoadError.value = error?.message || 'Failed to get project-related tasks';
    
    // Display specific error message instead of generic one
    let errorMessage = 'Failed to get project-related tasks';
    
    // If it's an error we've handled, show specific error message
    if (error.response && error.response.status === 404) {
      errorMessage = 'No related task information found, might be incorrect API path';
      console.warn('API endpoint not found. Please check the API path configuration.');
    } else if (error instanceof Error && error.message) {
      errorMessage = error.message;
    } else if (error.response?.data?.message) {
      errorMessage = error.response.data.message;
    }
    
    ElMessage({
      message: errorMessage,
      type: 'warning',
      duration: 5000,
      showClose: true
    });

    projectTasks.value = [];
  } finally {
    tasksLoading.value = false;
  }
};

const editProject = async (project: Project) => {
  // Set loading state
  loading.value = true;
  isEditing.value = true;
  
  try {
    // Set basic project information
    projectForm.value = {
      id: project.id,
      title: project.title,
      description: project.description || '',
      category: project.category || '',
      requirements: project.requirements || '',
      resources: project.resources || '',
      status: project.status,
      supervisorId: project.supervisorId,
      assigneeId: project.assigneeId // Make sure to load assigneeId field
    };
    
    // Record project assignment status
    if (project.assigneeId) {
      console.log(`Project assigned to student(ID:${project.assigneeId}, Name:${project.assigneeName || 'Unknown'})`);
    }
    
    if (project.startTime && project.endTime) {
      startTime.value = project.startTime;
      endTime.value = project.endTime;
    } else {
      startTime.value = null;
      endTime.value = null;
    }
    
    // Clear existing task list
    newProjectTasks.value = [];
    
    // Load project-related tasks
    const tasks = await getProjectTasks(project.id);
    console.log('Retrieved project-related tasks:', tasks);
    
    // Add tasks to edit form
    if (tasks && tasks.length > 0) {
      // Convert tasks to required format for editing
      newProjectTasks.value = tasks.map(task => ({
        id: task.id,
        title: task.title,
        description: task.description || '',
        priority: task.priority || 'Medium',
        status: task.status || 'Not Started',
        startTime: task.startTime || null,
        endTime: task.endTime || null
      }));
    }
    
    // Show edit dialog
    projectFormDialogVisible.value = true;
  } catch (error) {
    console.error('Failed to load project tasks:', error);
    ElMessage.error('Failed to load project tasks, please try again');
  } finally {
    loading.value = false;
  }
};

const deleteProjectItem = async (id: number) => {
  loading.value = true;
  try {
    const success = await deleteProject(id);
    if (success) {
      ElMessage.success('Project deleted successfully');
      projects.value = projects.value.filter(project => project.id !== id);
      
      // 关闭项目详情对话框，防止重复
      if (currentProject.value && currentProject.value.id === id) {
        detailsDialogVisible.value = false;
        currentProject.value = null;
      }
      
      // totalProjects will be updated by the computed property
    } else {
      ElMessage.error('Failed to delete project');
    }
  } catch (error) {
    console.error('Failed to delete project:', error);
    ElMessage.error('Failed to delete project');
  } finally {
    loading.value = false;
  }
};

const openAssignDialog = (project: Project) => {
  if (project.assigneeId) {
    ElMessage.warning('This project has already been assigned to a student');
    return;
  }
  
  projectToAssign.value = project;
  selectedStudentId.value = null;
  fetchStudents();
  assignDialogVisible.value = true;
};

const fetchStudents = async () => {
  studentsLoading.value = true;
  try {
    students.value = await getStudents();
    console.log('Retrieved student data:', students.value);
    if (students.value.length === 0) {
      ElMessage.warning('No assignable students found');
    }
  } catch (error) {
    console.error('Failed to get student data:', error);
    ElMessage.error('Failed to get student data, please try again later');
    students.value = [];
  } finally {
    studentsLoading.value = false;
  }
};

// Helper function: Assign all tasks under a project to a specific student
const assignProjectTasksToStudent = async (projectId: number, studentId: number) => {
  try {
    // Get all tasks under the project
    const tasks = await getProjectTasks(projectId);
    
    if (tasks.length === 0) {
      console.log('No tasks need to be assigned under this project');
      return;
    }
    
    console.log(`Attempting to assign ${tasks.length} tasks under project(ID:${projectId}) to student(ID:${studentId})`);
    
    // Create a task assignment Promise array
    const assignPromises = tasks.map(task => 
      assignTaskToStudent(task.id, studentId)
        .catch(error => {
          console.error(`Task(ID:${task.id}) assignment failed:`, error);
          return null; // Return null for failed assignment, but don't interrupt other task assignments
        })
    );
    
    // Wait for all task assignments to complete
    const results = await Promise.all(assignPromises);
    
    // Calculate successfully assigned task count
    const successCount = results.filter(result => result !== null).length;
    
    console.log(`Successfully assigned ${successCount}/${tasks.length} tasks to student`);
    
    return {
      total: tasks.length,
      success: successCount,
      failed: tasks.length - successCount
    };
  } catch (error) {
    console.error('Failed to assign project tasks:', error);
    throw error;
  }
};

const handleAssignProject = async () => {
  if (!projectToAssign.value || !selectedStudentId.value) {
    ElMessage.warning('Please select a student to assign');
    return;
  }
  
  loading.value = true;
  try {
    // Assign project to student
    const result = await assignProjectToStudent(projectToAssign.value.id, selectedStudentId.value);
    ElMessage.success('Project assigned successfully');
    
    // Update local data
    const index = projects.value.findIndex(p => p.id === projectToAssign.value?.id);
    if (index !== -1) {
      projects.value[index] = result;
    }
    
    // If currently in details page, also update current project
    if (currentProject.value && currentProject.value.id === projectToAssign.value.id) {
      currentProject.value = result;
    }
    
    // Assign all tasks under the project to the same student
    try {
      const assignTaskResult = await assignProjectTasksToStudent(projectToAssign.value.id, selectedStudentId.value);
      
      if (assignTaskResult && assignTaskResult.total > 0) {
        if (assignTaskResult.success === assignTaskResult.total) {
          ElMessage.success(`Successfully assigned ${assignTaskResult.success} tasks to student`);
        } else {
          ElMessage.warning(`Tasks partially assigned: ${assignTaskResult.success}/${assignTaskResult.total} tasks have been assigned`);
        }
        
        // If currently in details page, refresh task list
        if (currentProject.value && currentProject.value.id === projectToAssign.value.id) {
          fetchProjectTasks(currentProject.value.id);
        }
      }
    } catch (taskError) {
      console.error('Failed to assign tasks:', taskError);
      ElMessage.warning('Project assigned successfully, but task assignment failed. Please assign tasks manually');
    }
    
    assignDialogVisible.value = false;
    projectToAssign.value = null;
  } catch (error) {
    console.error('Failed to assign project:', error);
    ElMessage.error('Failed to assign project');
  } finally {
    loading.value = false;
  }
};

// Helper functions
const getStatusType = (status: string): 'primary' | 'success' | 'warning' | 'danger' | 'info' => {
  switch (status) {
    case 'Not Started': return 'primary';
    case 'In Progress': return 'warning';
    case 'Waiting for Review': return 'warning';
    case 'Completed': return 'success';
    case 'Pending Review': return 'warning';
    case 'Review Rejected': return 'danger';
    default: return 'primary';
  }
};

// Get task status style
const getTaskStatusType = (status: string): 'primary' | 'success' | 'warning' | 'danger' => {
  switch (status) {
    case 'Not Started': return 'primary';
    case 'In Progress': return 'warning';
    case 'Completed': return 'success';
    case 'Draft': return 'info';
    case 'Mid-term': return 'warning';
    case 'Final': return 'success';
    default: return 'primary';
  }
};

// Get task priority style
const getTaskPriorityType = (priority: string): 'primary' | 'success' | 'warning' | 'danger' => {
  switch (priority) {
    case 'High': return 'danger';
    case 'Medium': return 'warning';
    case 'Low': return 'success';
    default: return 'warning';
  }
};

// Submit project form
const submitProjectForm = async () => {
  if (!projectFormRef.value) return;
  
  await projectFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      
      try {
        // 确保状态始终为Not Started (对于新建项目)
        if (!isEditing.value) {
          projectForm.value.status = 'Not Started';
        }
        
        // Prepare project data
        const projectData = {
          ...projectForm.value
        };
        
        // Add time range
        if (startTime.value && endTime.value) {
          projectData.startTime = startTime.value;
          projectData.endTime = endTime.value;
        }
        
        let result;
        if (isEditing.value && projectForm.value.id) {
          // Update project
          result = await updateProject(projectForm.value.id, projectData);
          ElMessage.success('Project updated successfully');
          
          // Handle tasks in edit mode
          if (newProjectTasks.value.length > 0) {
            const projectId = projectForm.value.id;
            console.log('Edit mode: Processing project-related tasks', newProjectTasks.value);
            
            // Check if project is assigned to a student
            const isAssignedToStudent = result.assigneeId !== null && result.assigneeId !== undefined;
            console.log('Project assignment status:', isAssignedToStudent ? `Assigned to student ID: ${result.assigneeId}` : 'Not assigned');
            
            try {
              // 先获取项目现有的所有任务，用于检查哪些任务需要更新，哪些需要新建，哪些需要删除
              const existingTasks = await getProjectTasks(projectId);
              console.log('Existing tasks:', existingTasks);
              
              // 用于记录已处理的任务ID (更新后的任务)
              const processedTaskIds = [];
              
              // 处理表单中的任务（更新现有任务或创建新任务）
              const taskPromises = [];
              
              for (const task of newProjectTasks.value) {
                const taskData = {
                  ...task,
                  supervisorId: userStore.user.id,
                  projectId: projectId
                };
                
                // 如果项目已分配给学生，则任务也分配给该学生
                if (isAssignedToStudent) {
                  taskData.assigneeId = result.assigneeId;
                }
                
                // 如果当前任务没有设置时间，但项目有时间，则使用项目时间
                if ((!taskData.startTime || !taskData.endTime) && startTime.value && endTime.value) {
                  taskData.startTime = taskData.startTime || startTime.value;
                  taskData.endTime = taskData.endTime || endTime.value;
                }
                
                // 如果任务有ID，更新任务；否则创建新任务
                if (task.id) {
                  console.log(`Updating existing task with ID: ${task.id}`);
                  processedTaskIds.push(task.id);
                  taskPromises.push(updateTask(task.id, taskData));
                } else {
                  console.log('Creating new task');
                  taskPromises.push(createTask(taskData));
                }
              }
              
              // 等待所有任务更新/创建完成
              await Promise.all(taskPromises);
              
              // 检查是否有需要删除的任务（存在于现有任务但不在表单中的任务）
              const existingTaskIds = existingTasks.map(task => task.id);
              
              // 从现有任务中过滤出不在newProjectTasks中的任务ID
              const newTaskIds = newProjectTasks.value
                .filter(task => task.id) // 只考虑有ID的任务（已存在的任务）
                .map(task => task.id);
              
              // 找出需要删除的任务（在existingTaskIds中但不在newTaskIds中）
              const tasksToDelete = existingTaskIds.filter(id => !newTaskIds.includes(id));
              
              if (tasksToDelete.length > 0) {
                console.log(`Found ${tasksToDelete.length} tasks to delete: ${tasksToDelete.join(', ')}`);
                
                try {
                  const deletePromises = tasksToDelete.map(taskId => {
                    console.log(`Deleting task with ID: ${taskId}`);
                    return deleteTaskApi(taskId)
                      .catch(err => {
                        console.error(`Failed to delete task ${taskId}:`, err);
                        throw new Error(`Failed to delete task ${taskId}: ${err.message || 'Unknown error'}`);
                      });
                  });
                  
                  // 等待所有删除操作完成
                  await Promise.all(deletePromises);
                } catch (deleteError) {
                  console.error('Error during task deletion:', deleteError);
                  ElMessage.error('Some tasks could not be deleted. Project saved but with inconsistent state.');
                  // 即使有删除失败也继续执行，但记录错误和警告用户
                }
              }
              
              // 根据项目分配状态显示不同的成功提示
              if (isAssignedToStudent) {
                ElMessage.success(`Successfully updated project tasks and automatically assigned to the responsible student`);
              } else {
                ElMessage.success(`Successfully updated project tasks`);
              }
            } catch (error) {
              console.error('Failed to process project tasks:', error);
              ElMessage.error('Failed to update some tasks');
              // 继续执行，不要因为任务处理失败而中断整个流程
            }
          }
        } else {
          // Create project
          result = await createProject(projectData);
          ElMessage.success('Project created successfully');
          
          // If there are related tasks, create tasks
          if (newProjectTasks.value.length > 0 && result.id) {
            const projectId = result.id;
            
            // Check if the newly created project is assigned to a student (usually not assigned)
            const isAssignedToStudent = result.assigneeId !== null && result.assigneeId !== undefined;
            console.log('New project assignment status:', isAssignedToStudent ? `Assigned to student ID: ${result.assigneeId}` : 'Not assigned');
            
            const promises = newProjectTasks.value.map(task => {
              // Create task data
              const taskData = {
                ...task,
                supervisorId: userStore.user.id,
                projectId: projectId
              };
              
              // If project is assigned to a student, tasks are also assigned to that student
              if (isAssignedToStudent) {
                taskData.assigneeId = result.assigneeId;
              }
              
              // If current task doesn't have time set, but project has time, use project time
              if ((!taskData.startTime || !taskData.endTime) && startTime.value && endTime.value) {
                taskData.startTime = taskData.startTime || startTime.value;
                taskData.endTime = taskData.endTime || endTime.value;
              }
              
              // Create task
              return createTask(taskData);
            });
            
            // Wait for all task creation to complete
            await Promise.all(promises);
            
            // Give different success tips based on project assignment status
            if (isAssignedToStudent) {
              ElMessage.success(`Successfully created ${newProjectTasks.value.length} related tasks and automatically assigned to the responsible student`);
            } else {
              ElMessage.success(`Successfully created ${newProjectTasks.value.length} related tasks`);
            }
          }
        }
        
        projectFormDialogVisible.value = false;
        fetchProjects(); // Refresh project list
      } catch (error) {
        console.error('Failed to submit project:', error);
        ElMessage.error('Failed to submit project');
      } finally {
        loading.value = false;
      }
    } else {
      ElMessage.error('Please fill in all required fields');
    }
  });
};

// Open add task dialog
const openAddTaskDialog = () => {
  // Check if project is in Review Rejected or Waiting for Review status
  if (currentProject.value && (currentProject.value.status === 'Review Rejected' || currentProject.value.status === 'Waiting for Review')) {
    ElMessage.warning(`Cannot add tasks to project in ${currentProject.value.status} status`);
    return;
  }
  
  // 检查当前项目是否已分配给学生
  let assigneeId = null;
  if (currentProject.value && currentProject.value.assigneeId) {
    assigneeId = currentProject.value.assigneeId;
    console.log('Pre-assigning task to current project student ID:', assigneeId);
  }
  
  // Initialize task form
  taskForm.value = {
    title: '',
    description: '',
    priority: 'Medium',
    status: 'Not Started',
    supervisorId: userStore.user.id,
    projectId: currentProject.value?.id || null,
    assigneeId: assigneeId, // 使用预设的学生ID
    completed: false,
    startTime: null,
    endTime: null
  };
  
  console.log('Add task form data:', taskForm.value);
  taskFormVisible.value = true;
};

// Submit task form
const submitTaskForm = async () => {
  if (!taskForm.value.title) {
    ElMessage.warning('Please enter task title');
    return;
  }
  
  if (!taskForm.value.projectId) {
    ElMessage.warning('Cannot link to current project');
    return;
  }
  
  // 验证时间范围
  if (taskForm.value.startTime && taskForm.value.endTime) {
    const start = new Date(taskForm.value.startTime).getTime();
    const end = new Date(taskForm.value.endTime).getTime();
    if (start > end) {
      ElMessage.error('结束时间不能早于开始时间');
      return;
    }
  }
  
  loading.value = true;
  try {
    // Ensure projectId field is retained
    const taskData = {
      ...taskForm.value,
      projectId: currentProject.value?.id || taskForm.value.projectId
    };
    
    console.log('Submit task data:', taskData);
    
    // Create task
    await createTask(taskData);
    ElMessage.success('Task created successfully');
    
    // Refresh task list
    if (currentProject.value?.id) {
      fetchProjectTasks(currentProject.value.id);
    }
    
    // Close dialog
    taskFormVisible.value = false;
  } catch (error) {
    console.error('Failed to create task:', error);
    ElMessage.error('Failed to create task');
  } finally {
    loading.value = false;
  }
};

// Delete task
const handleDeleteTask = async (task: Task) => {
  ElMessageBox.confirm('Are you sure you want to delete this task?', 'Confirm', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning'
  }).then(async () => {
    loading.value = true;
    try {
      const success = await deleteTaskApi(task.id);
      if (success) {
        ElMessage.success('Task deleted successfully');
        
        // Only refresh the task list of the current project
        if (currentProject.value && currentProject.value.id) {
          fetchProjectTasks(currentProject.value.id);
        }
        
        // Update project status, but don't refresh the entire project list
        if (currentProject.value && currentProject.value.id) {
          try {
            // Get the latest project information
            const updatedProject = await getProjectDetail(currentProject.value.id);
            if (updatedProject) {
              currentProject.value = updatedProject;
              
              // Update project status in the project list
              const index = projects.value.findIndex(p => p.id === updatedProject.id);
              if (index !== -1) {
                projects.value[index] = updatedProject;
              }
            }
          } catch (error) {
            console.error('Failed to update project information:', error);
          }
        }
      } else {
        ElMessage.error('Failed to delete task');
      }
    } catch (error) {
      console.error('Failed to delete task:', error);
      ElMessage.error('Failed to delete task');
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // User canceled deletion
  });
};

// Add new task
const addNewTask = () => {
  // 添加表单验证，确保任务标题不为空
  if (!newTaskForm.value.title || newTaskForm.value.title.trim() === '') {
    ElMessage.warning('Please enter task title');
    return;
  }
  
  // Ensure task status is 'Not Started' for 'Pending Review' projects
  if (projectForm.value.status === 'Pending Review') {
    newTaskForm.value.status = 'Not Started';
  }
  
  // If editing a task, update that task
  if (editingTaskIndex.value >= 0) {
    newProjectTasks.value[editingTaskIndex.value] = {...newTaskForm.value};
    editingTaskIndex.value = -1;
  } else {
    // Otherwise add new task
    newProjectTasks.value.push({...newTaskForm.value});
  }
  
  // Reset form
  newTaskForm.value = {
    title: '',
    description: '',
    priority: 'Medium',
    status: 'Not Started',
    startTime: null,
    endTime: null
  };
  
  // Close dialog
  newTaskFormVisible.value = false;
};

// Edit task when creating project
const editNewTask = (index: number) => {
  // Set edit index
  editingTaskIndex.value = index;
  
  // Set form data
  const task = newProjectTasks.value[index];
  newTaskForm.value = {
    title: task.title,
    description: task.description || '',
    priority: task.priority || 'Medium',
    status: task.status || 'Not Started', // 保持原状态，但在表单中不显示
    startTime: task.startTime || null,
    endTime: task.endTime || null
  };
  
  // Open dialog
  newTaskFormVisible.value = true;
};

// Remove task when creating project
const removeNewTask = (index: number) => {
  // 获取要删除的任务
  const taskToRemove = newProjectTasks.value[index];
  
  // 从数组中移除任务
  newProjectTasks.value.splice(index, 1);
  
  // 如果是编辑项目且任务有ID，记录日志便于调试
  if (isEditing.value && taskToRemove && taskToRemove.id) {
    console.log(`Task with ID ${taskToRemove.id} marked for deletion`);
  }
};

// Open new task dialog
const openNewTaskDialog = () => {
  // Reset index
  editingTaskIndex.value = -1;
  
  // Initialize task form
  newTaskForm.value = {
    title: '',
    description: '',
    priority: 'Medium',
    status: 'Not Started',
    startTime: null,
    endTime: null
  };
  
  // Open dialog
  newTaskFormVisible.value = true;
};

// Batch select tasks dialog
const openBatchSelectTasksDialog = async () => {
  // Clear selected tasks
  selectedTasks.value = [];
  
  // Load available tasks
  availableTasksLoading.value = true;
  try {
    availableTasks.value = await getAvailableTasks(userStore.user.id);
  } catch (error) {
    console.error('Failed to get available tasks:', error);
    ElMessage.error('Failed to get available tasks');
  } finally {
    availableTasksLoading.value = false;
  }
  
  batchSelectTasksVisible.value = true;
};

const handleTaskSelectionChange = (selected: Task[]) => {
  selectedTasks.value = selected;
};

const addSelectedTasks = () => {
  if (selectedTasks.value.length === 0) {
    ElMessage.warning('Please select at least one task');
    return;
  }
  
  // Add selected tasks to new project task list
  selectedTasks.value.forEach(task => {
    // Check if the same task has already been added
    const exists = newProjectTasks.value.some(t => 
      t.title === task.title && t.description === task.description
    );
    
    if (!exists) {
      newProjectTasks.value.push({
        title: task.title,
        description: task.description,
        priority: task.priority || 'Medium',
        status: task.status || 'Not Started',
        startTime: task.startTime || null,
        endTime: task.endTime || null
      });
    }
  });
  
  ElMessage.success(`Added ${selectedTasks.value.length} tasks`);
  batchSelectTasksVisible.value = false;
};

const viewTaskSubmissions = async (task: Task) => {
  currentSubmissionTask.value = task;
  submissionsDialogVisible.value = true;
  submissions.value = []; // Clear previous data
  
  try {
    console.log('Start getting task submission records, Task ID:', task.id);
    const result = await getTaskSubmissions(task.id);
    
    if (result && result.length > 0) {
      console.log('Number of submission records:', result.length);
      console.log('Submission record details:', JSON.stringify(result[0]));
      submissions.value = result;
    } else {
      console.log('No submission records for this task');
    }
  } catch (error) {
    console.error('Failed to get task submission records:', error);
    ElMessage.error('Failed to get task submission records');
  }
};

// Download submission file
const downloadSubmission = (submission: TaskSubmission) => {
  try {
    console.log('Start downloading file:', submission);
    
    // Get authorization token
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('Authorization expired, please log in again');
      return;
    }
    
    // Show downloading tip
    const loadingInstance = ElLoading.service({
      lock: true,
      text: 'Preparing to download file...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    // Create an a tag to download file
    const link = document.createElement('a');
    link.href = `/api/supervisor/submissions/${submission.id}/download`;
    link.setAttribute('download', submission.originalFilename);
    
    // To ensure the request includes authorization header, we use Fetch API
    fetch(link.href, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    .then(response => {
      loadingInstance.close();
      
      if (!response.ok) {
        if (response.status === 404) {
          throw new Error('File does not exist or has been deleted');
        } else if (response.status === 403) {
          throw new Error('You do not have permission to download this file');
        } else if (response.status === 401) {
          throw new Error('Authorization expired, please log in again');
        } else {
          throw new Error(`Download failed: ${response.status}`);
        }
      }
      return response.blob();
    })
    .then(blob => {
      // Check if it's an error message instead of a file
      if (blob.type === 'application/json') {
        // If it's JSON, it might be an error message
        return blob.text().then(text => {
          try {
            const errorData = JSON.parse(text);
            throw new Error(errorData.message || 'Download failed, please try again later');
          } catch (e) {
            throw new Error('Download failed, file format incorrect');
          }
        });
      }
      
      // Confirm it's a file blob, create download link
      const url = window.URL.createObjectURL(blob);
      const downloadLink = document.createElement('a');
      downloadLink.href = url;
      downloadLink.download = submission.originalFilename;
      document.body.appendChild(downloadLink);
      downloadLink.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(downloadLink);
      
      ElMessage.success('File downloaded successfully');
    })
    .catch(error => {
      loadingInstance.close();
      console.error('Failed to download file:', error);
      
      // Show user-friendly error message
      ElMessageBox.alert(
        `Failed to download file "${submission.originalFilename}": ${error.message}`, 
        'Download Error', 
        {
          confirmButtonText: 'OK',
          type: 'error',
          callback: () => {
            // Optional: Provide retry or other solution suggestions
            ElMessage({
              type: 'info',
              message: 'Please contact admin to check if the file exists or try uploading the file again'
            });
          }
        }
      );
    });
  } catch (error) {
    console.error('Download file operation failed:', error);
    ElMessage.error('Failed to download file');
  }
};

// Format file size
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else {
    return (size / 1024 / 1024).toFixed(2) + ' MB';
  }
};

// Check pending review project count
const checkPendingReviews = async () => {
  try {
    const pendingProjects = await getPendingReviewProjects(userStore.user.id);
    pendingReviewCount.value = pendingProjects?.length || 0;
  } catch (error) {
    console.error('Failed to get pending review project count:', error);
  }
};

// Review project application
const approveProjectApplication = async () => {
  if (!projectToReview.value) {
    ElMessage.warning('Please select a project to review');
    return;
  }
  
  reviewing.value = true;
  try {
    const result = await reviewProjectApplication(projectToReview.value.id, true);
    ElMessage.success('Project approved');
    
    // Update local data
    const index = projects.value.findIndex(p => p.id === projectToReview.value.id);
    if (index !== -1) {
      projects.value[index] = result;
    }
    
    // If currently in details page, also update current project
    if (currentProject.value && currentProject.value.id === projectToReview.value.id) {
      currentProject.value = result;
    }
    
    reviewDialogVisible.value = false;
    projectToReview.value = null;
  } catch (error) {
    console.error('Failed to review project:', error);
    ElMessage.error('Failed to review project');
  } finally {
    reviewing.value = false;
    // Update pending review count to decrease the badge number
    checkPendingReviews();
  }
};

const rejectProjectApplication = async () => {
  if (!projectToReview.value) {
    ElMessage.warning('Please select a project to review');
    return;
  }
  
  reviewing.value = true;
  try {
    const result = await reviewProjectApplication(projectToReview.value.id, false);
    ElMessage.success('Project application rejected');
    
    // Update local data
    const index = projects.value.findIndex(p => p.id === projectToReview.value.id);
    if (index !== -1) {
      projects.value[index] = result;
    }
    
    // If currently in details page, also update current project
    if (currentProject.value && currentProject.value.id === projectToReview.value.id) {
      currentProject.value = result;
    }
    
    reviewDialogVisible.value = false;
    projectToReview.value = null;
  } catch (error) {
    console.error('Failed to review project:', error);
    ElMessage.error('Failed to review project');
  } finally {
    reviewing.value = false;
    // Update pending review count to decrease the badge number
    checkPendingReviews();
  }
};

const openReviewDialog = (project: Project) => {
  projectToReview.value = project;
  reviewDialogVisible.value = true;
};

// Load project evaluation
const loadProjectEvaluation = async (projectId: number) => {
  try {
    evaluationLoading.value = true;
    const evaluation = await getProjectEvaluation(projectId);
    currentEvaluation.value = evaluation;
  } catch (error: any) {
    // Ignore 404 or no data errors, as the project might not have evaluation yet
    if (error.response && error.response.status === 404) {
      console.log('Project has no evaluation yet, this is normal');
      currentEvaluation.value = null;
      
      // Reset evaluation form to default values
      evaluationForm.value.score = 80;
      evaluationForm.value.comment = '';
    } else if (!error.response || error.response.status !== 404) {
      console.error('Failed to get project evaluation:', error);
      // Don't show error message, handle silently
      
      currentEvaluation.value = null;
      
      // Reset evaluation form to default values
      evaluationForm.value.score = 80;
      evaluationForm.value.comment = '';
    }
  } finally {
    evaluationLoading.value = false;
  }
};

// Submit project evaluation
const submitEvaluation = async () => {
  if (!currentProject.value) return;
  
  try {
    evaluationLoading.value = true;
    console.log('Submit evaluation data:', {
      projectId: currentProject.value.id,
      score: evaluationForm.value.score,
      comment: evaluationForm.value.comment
    });
    
    const response = await evaluateProject(
      currentProject.value.id,
      evaluationForm.value.score,
      evaluationForm.value.comment
    );
    
    console.log('Evaluation submission response:', response);
    
    // Validate returned data validity
    if (response && response.id && response.score !== undefined) {
      currentEvaluation.value = response;
      ElMessage.success('Evaluation submitted successfully');
      
      if (currentProject.value) {
        const updatedProject = await getProjectDetail(currentProject.value.id);
        currentProject.value = updatedProject;
        

        const index = projects.value.findIndex(p => p.id === currentProject.value?.id);
        if (index !== -1) {
          projects.value[index] = updatedProject;
        }
      }
    } else {
      // Data incomplete, maintain form state
      console.error('Evaluation data returned by API is incomplete:', response);
      currentEvaluation.value = null; // Ensure form continues to display
      ElMessage.warning('Evaluation submitted successfully, but cannot display evaluation details');
    }
  } catch (error: any) {
    console.error('Evaluation submission failed:', error);
    // Maintain form state
    currentEvaluation.value = null;
    ElMessage.error(`Evaluation submission failed: ${error.message || 'Unknown error'}`);
  } finally {
    evaluationLoading.value = false;
  }
};

// Edit project evaluation
const editEvaluation = () => {
  if (currentEvaluation.value) {
    evaluationForm.value.score = currentEvaluation.value.score;
    evaluationForm.value.comment = currentEvaluation.value.comment || '';
    currentEvaluation.value = null;
  }
};

// Delete project evaluation
const deleteEvaluation = async () => {
  if (!currentProject.value) return;
  
  try {
    await ElMessageBox.confirm('Are you sure you want to delete this evaluation?', 'Warning', {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning'
    });
    
    evaluationLoading.value = true;
    const success = await deleteProjectEvaluation(currentProject.value.id);
    if (success) {
      currentEvaluation.value = null;
      
      // Reset evaluation form
      evaluationForm.value.score = 80;
      evaluationForm.value.comment = '';
      
      ElMessage.success('Evaluation deleted');
    } else {
      ElMessage.error('Failed to delete evaluation');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('Failed to delete evaluation:', error);
      ElMessage.error(`Failed to delete evaluation: ${error.message || 'Unknown error'}`);
    }
  } finally {
    evaluationLoading.value = false;
  }
};

const finalizeProject = async (projectId: number) => {
  try {
    console.log('Finalizing project:', projectId);
    
    await ElMessageBox.confirm(
      'Are you sure you want to finalize this project? This action will mark the project as completed and archive it.',
      'Finalize Project',
      {
        confirmButtonText: 'Finalize',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }
    );
    
    // Call API to update project status
    loading.value = true;
    await updateProjectStatus(projectId, 'Finalized');
    
    // Update current project status in UI
    if (currentProject.value && currentProject.value.id === projectId) {
      currentProject.value.status = 'Finalized';
    }
    
    // Refresh project list
    await fetchProjects();
    
    ElMessage.success('Project has been finalized successfully');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to finalize project:', error);
      ElMessage.error('Failed to finalize project');
    }
  } finally {
    loading.value = false;
  }
};

const disablePastDates = (time) => {

  return time.getTime() < Date.now() - 8.64e7; // 8.64e7 是一天的毫秒数，允许选择今天
};


const updateTaskStatus = async (taskId, status) => {
  try {
    await updateTaskStatusApi(taskId, { status: status });
    console.log(`Task ${taskId} status updated to ${status}`);
  } catch (error) {
    console.error(`Failed to update task ${taskId} status:`, error);
  }
};


const validateTimeRange = () => {
  if (startTime.value && endTime.value) {
    const start = new Date(startTime.value);
    const end = new Date(endTime.value);
    
    if (end < start) {
      ElMessage.error('结束时间不能小于开始时间');
      endTime.value = null;
    }
  }
};

// 添加任务时间验证函数
const validateTaskTimeRange = () => {
  if (newTaskForm.value.startTime && newTaskForm.value.endTime) {
    const start = new Date(newTaskForm.value.startTime);
    const end = new Date(newTaskForm.value.endTime);
    
    if (end < start) {
      ElMessage.error('结束时间不能小于开始时间');
      newTaskForm.value.endTime = null;
    }
  }
};


const disableBeforeStartDate = (time) => {
  const now = Date.now() - 8.64e7;
  

  if (!startTime.value) {
    return time.getTime() < now;
  }
  

  const startDateTime = new Date(startTime.value).getTime();
  return time.getTime() < startDateTime || time.getTime() < now;
};


const disableBeforeTaskStartDate = (time) => {
  const now = Date.now() - 8.64e7;
  
  if (!newTaskForm.value.startTime) {
    return time.getTime() < now;
  }
  

  const startDateTime = new Date(newTaskForm.value.startTime).getTime();
  return time.getTime() < startDateTime || time.getTime() < now;
};

// Add handleProjectDialogClosed function to clean up resources when the project dialog is closed
const handleProjectDialogClosed = () => {
  // Clean up resources
  projectTasks.value = [];
  // 移除这一行，避免清空当前项目数据导致再次查看时出现问题
  // currentProject.value = null;
  tasksLoadError.value = null;
  currentEvaluation.value = null;
};


const handleSubmissionsDialogClosed = () => {
  submissions.value = [];
  currentSubmissionTask.value = null;
};

const hasEvaluation = (project: Project) => {
  // 1. 查看项目详情已加载评估信息的情况
  if (currentProject.value && currentProject.value.id === project.id && currentEvaluation.value) {
    return true;
  }
  
  // 2. 根据项目状态判断
  if (project.status === 'Completed') {
    return true;
  }
  
  return false;
};

const confirmDeleteProject = (project: Project) => {
  // Check if the project can be deleted
  if (!canDeleteProject(project)) {
    ElMessage.warning(getDeleteButtonTitle(project));
    return;
  }
  
  // Confirmation dialog
  ElMessageBox.confirm(
    'Are you sure you want to delete this project? This action cannot be undone and all associated tasks will be deleted.', 
    'Delete Confirmation', 
    {
      confirmButtonText: 'Delete',
      cancelButtonText: 'Cancel',
      type: 'warning'
    }
  ).then(async () => {
    loading.value = true;
    try {
      // First query the project-related tasks
      if (project.id) {
        const tasks = await getProjectTasks(project.id);
        if (tasks.length > 0) {
          // If there are tasks, confirm again
          return ElMessageBox.confirm(
            `This project contains ${tasks.length} associated tasks. Are you sure you want to delete them all?`, 
            'Second Confirmation', 
            {
              confirmButtonText: 'Delete',
              cancelButtonText: 'Cancel',
              type: 'warning'
            }
          );
        }
        return true; // No tasks, delete directly
      }
    } catch (error) {
      console.error('Failed to get project tasks:', error);
      ElMessage.error('Failed to get project tasks');
      loading.value = false;
      throw error; // Interrupt the deletion process
    }
  }).then(async (confirm) => {
    if (!confirm) return; // If the user cancels in the second confirmation, don't execute the deletion
    
    try {
      const success = await deleteProject(project.id);
      if (success) {
        ElMessage.success('Project deleted successfully');
        // Remove the project from the list
        projects.value = projects.value.filter(p => p.id !== project.id);
        // If currently viewing the details of this project, close the details dialog
        if (detailsDialogVisible.value && currentProject.value && currentProject.value.id === project.id) {
          detailsDialogVisible.value = false;
          currentProject.value = null;
        }
        // Refresh the project list
        fetchProjects();
      } else {
        ElMessage.error('Failed to delete project');
      }
    } catch (error) {
      console.error('Failed to delete project:', error);
      ElMessage.error('Failed to delete project');
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // User cancelled deletion
    loading.value = false;
  });
};

const canDeleteProject = (project: Project): boolean => {
  // Can only delete projects if:
  // 1. The project has not been assigned to a student yet (no assigneeId)
  // 2. The project is in "Pending Review" status (student's application waiting for review)
  
  // Check if project has been assigned to a student
  if (project.assigneeId) {
    return false;
  }
  
  // Check project status
  // Projects in "Pending Review" status can be deleted (rejecting the application)
  // Projects that are not assigned to any student can be deleted
  if (project.status === 'Pending Review' || project.status === 'Not Started') {
    return true;
  }
  
  // All other statuses (In Progress, Completed, etc.) cannot be deleted
  return false;
};

const getDeleteButtonTitle = (project: Project): string => {
  if (project.assigneeId && project.status !== 'Pending Review') {
    return 'Cannot delete assigned project';
  } else if (project.status === 'In Progress') {
    return 'Cannot delete project in progress';
  } else if (project.status === 'Completed') {
    return 'Cannot delete completed project';  
  } else if (canDeleteProject(project)) {
    return 'Delete project';
  } else {
    return 'Cannot delete this project';
  }
};
</script>

<style scoped>
.project-management {
  padding: 10px;
  height: calc(100vh - 60px); /* 设置高度为视口高度减去顶部导航栏高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

.box-card {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  position: sticky;
  bottom: 0;
  background-color: #fff;
  padding: 5px 0;
  z-index: 1;
}

.project-tabs {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.project-description,
.project-requirements,
.project-resources {
  white-space: pre-wrap;
  word-break: break-word;
}

.project-resources {
  white-space: pre-wrap;
  max-height: 200px;
  overflow-y: auto;
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.task-section {
  margin-top: 20px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.empty-task {
  padding: 20px;
  text-align: center;
}

.submission-list {
  margin-top: 20px;
}

.task-info {
  margin-bottom: 20px;
}

.no-submissions {
  padding: 20px 0;
  text-align: center;
}

.task-create-section {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.empty-tasks-tip {
  margin: 20px 0;
  text-align: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.review-content {
  padding: 20px;
}

.review-badge {
  margin-left: 5px;
}

.project-evaluation-section {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.evaluation-details {
  margin-top: 20px;
}

.task-loading-tip {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.auto-assign-tip {
  margin-top: 10px;
  font-size: 0.8em;
  color: #909399;
}

/* Ensure tables can scroll horizontally */
.el-table {
  width: 100%;
  overflow-x: auto;
}
</style>

 